<template>
  <div class="charts-container">

<div class="device-status-container">
  <el-row :gutter="20">
    <el-col :span="6" v-for="(status, index) in deviceStatuses" :key="index">
      <div class="status-card">
        <el-row :gutter="10"> <!-- 减少行间距 -->
          <el-col :span="7" class="icon-column">
            <div class="icon">
              <img :src="status.iconSrc" alt="Icon" :style="{ width: '48px', height: '48px' }" />
            </div>
          </el-col>
          <el-col :span="17" class="info-column">
            <div class="count">{{ status.count }}</div>
            <div class="label">{{ status.label }}</div>
          </el-col>
        </el-row>
      </div>
    </el-col>
  </el-row>
</div>


    <!-- Input for changing the daily quota -->
    <div class="input-container" style="padding-top: 20px;">
      <label for="dailyQuota">每日规定产量:</label>
      <el-input-number id="dailyQuota" v-model="dailyQuota" :min="0" @change="updateDailyQuota"></el-input-number>
    </div>

    <!-- Line Chart -->
    <div ref="lineChart" class="chart full-width"></div>

    <!-- 搜索框 -->
    <el-form :inline="true" :model="searchProduck" class="demo-form-inline">
      <el-form-item label="时间区域">
        <el-date-picker v-model="searchProduck.startDate" type="date" placeholder="选择起始时间" format="yyyy-MM-dd"
          value-format="yyyy-MM-dd">
        </el-date-picker>
        <el-date-picker v-model="searchProduck.endDate" type="date" placeholder="选择结束时间" format="yyyy-MM-dd"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="销售额">
        <el-input v-model="searchProduck.quantitySalse" placeholder="输入查询销售额大于此数"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="checkCProduck">查询</el-button>
        <!-- <el-button @click="cleanClient">重置</el-button> -->
      </el-form-item>
    </el-form>

    <!-- 表格模块 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="itemCode" label="物料编码" width="180">
      </el-table-column>
      <el-table-column prop="itemName" label="物料名称" width="180">
      </el-table-column>
      <el-table-column prop="specification" label="规格型号">
      </el-table-column>
      <el-table-column prop="unitOfMeasure" label="单位">
      </el-table-column>
      <el-table-column prop="quantitySalse" label="出库数量">
      </el-table-column>
      <el-table-column prop="warehouseName" label="库区名称">
      </el-table-column>
      <el-table-column prop="areaName" label="库位名称">
      </el-table-column>
    </el-table>
    <el-pagination :page-size="searchProduck.pageSize" :total="searchProduck.total" @current-change="searchChange"
      layout="prev, pager, next">
    </el-pagination>

  </div>
</template>

<script>
import qs from 'qs';
import * as echarts from 'echarts';
import axios from 'axios'; // 如果没有全局引入 axios，则需要在这里引入

export default {
  data() {
    return {
      deviceStatuses: [
        { iconSrc: require('@/assets/mainShowSvg/设备总数.svg'), count: 120, label: '设备总数' },
        { iconSrc: require('@/assets/mainShowSvg/运行中.svg'), count: 80, label: '运行中' },
        { iconSrc: require('@/assets/mainShowSvg/待机.svg'), count: 30, label: '待机' },
        { iconSrc: require('@/assets/mainShowSvg/故障.svg'), count: 10, label: '故障' }
      ],
      dayDateList: [], // 初始化为空数组，以防 undefined
      dailyQuota: 50, // 默认的每日规定产量
      myLineChart: null, // ECharts 实例
      //查询的表单
      searchProduck: {
        startDate: '',
        endDate: '',
        quantitySalse: '',
        pageSize: 5,
        pageNo: 1,
        total: 0,
      },
      tableData: []
    };
  },
  mounted() {
    this.checkAll();
    this.initLineChart();
    this.checkCProduck();
  },
  methods: {
    async checkAll() {
      try {
        const res = await axios.post("http://localhost:9970/emsSystem/api/ProductSalseLine/checkProduct");
        this.dayDateList = res.data.data;
        this.initLineChart();
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
    // 改变页码
    searchChange(value) {
      this.searchProduck.pageNo = value;
      this.checkCProduck();
    },
    //条件查询
    checkCProduck() {
      if (new Date(this.searchProduck.startDate).getTime() >= new Date(this.searchProduck.endDate).getTime()) {
        this.$message.error('开始日期必须早于结束日期');
        return;
      }
      let qsStr = qs.stringify(this.searchProduck);
      this.$axios.post("http://localhost:9970/emsSystem/api/ProductSalseLine/checkPage", qsStr).then((res) => {
        if (res.data.code === 200) {
          if (res.data.code === 200) {
            this.tableData = res.data.data.records
            this.searchProduck.pageNo = res.data.data.current
            this.searchProduck.pageSize = res.data.data.size
            this.searchProduck.total = res.data.data.total
          }
        }
      })
    },
    initLineChart() {
      if (!this.dayDateList.length) return;

      // 对数据进行排序以确保时间序列正确
      const sortedData = [...this.dayDateList].sort((a, b) => new Date(a.dayOfWeek) - new Date(b.dayOfWeek));

      // 更新 X 轴和 Y 轴数据
      const xAxisData = sortedData.map(item => item.dayOfWeek);
      const productionData = sortedData.map(item => item.dayOfMonth);

      // 初始化 ECharts 实例
      this.myLineChart = echarts.init(this.$refs.lineChart);

      // 设置图表配置项
      const lineOption = {
        title: {
          text: 'Weekly Production',
          left: 'left'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['每日出货量', '每日规定产量']
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '每日出货量',
            type: 'line',
            data: productionData,
            symbol: 'circle',
            symbolSize: 7,
            lineStyle: {
              color: 'blue'
            }
          },
          {
            name: '每日规定产量',
            type: 'line',
            data: Array(xAxisData.length).fill(this.dailyQuota),
            symbol: 'circle',
            symbolSize: 7,
            lineStyle: {
              color: 'red'
            }
          }
        ]
      };

      // 应用配置项并渲染图表
      this.myLineChart.setOption(lineOption);

      // 监听窗口大小变化，以便自动调整图表大小
      window.addEventListener('resize', () => this.myLineChart.resize());
    },
    updateDailyQuota(value) {
      // 更新图表的每日规定产量数据
      const xAxisData = this.dayDateList.map(item => item.dayOfWeek);
      const updatedProductionQuota = Array(xAxisData.length).fill(value);

      // 更新图表系列中的每日规定产量数据
      this.myLineChart.setOption({
        series: [{
          name: '每日规定产量',
          data: updatedProductionQuota
        }]
      });
    }
  },
  beforeDestroy() {
    // 移除监听器，防止内存泄漏
    window.removeEventListener('resize', this.myLineChart.resize);
  }
}
</script>

<style scoped>
.charts-container {
  width: 100%;
}

.input-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.input-container label {
  margin-right: 10px;
}

.chart {
  width: 100%;
  height: 400px;
}

@media (max-width: 768px) {
  .chart {
    margin-bottom: 20px;
  }
}


.device-status-container {
  margin-top: 20px;
}

.status-card {
  padding: 10px; /* 减少卡片内边距 */
  border: 1px solid #ebeef5;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.status-card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
}

.icon-column {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-right: 5px; /* 减少右边距以使图标与文本更接近 */
}

.info-column {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 5px; /* 减少左边距以使文本与图标更接近 */
}

.count {
  font-size: 24px;
  color: #303133;
  margin-bottom: 5px;
}

.label {
  font-size: 14px;
  color: #909399;
}
</style>